package cn.frh.pet.service.impl;

import cn.frh.basic.Exception.BusinessException;
import cn.frh.basic.service.impl.BaiduAiAuditServiceImpl;
import cn.frh.basic.service.impl.BaseServiceImpl;
import cn.frh.basic.util.*;
import cn.frh.order.domain.OrderPetAcquisition;
import cn.frh.order.mapper.OrderPetAcquisitionMapper;
import cn.frh.order.rocketmq.RocketMQProducerService;
import cn.frh.org.domain.Employee;
import cn.frh.org.domain.Shop;
import cn.frh.org.mapper.EmployeeMapper;
import cn.frh.org.mapper.ShopMapper;
import cn.frh.pet.domain.Pet;
import cn.frh.pet.domain.SearchMasterMsg;
import cn.frh.pet.domain.SearchMasterMsgAuditLog;
import cn.frh.pet.mapper.PetMapper;
import cn.frh.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.frh.pet.mapper.SearchMasterMsgMapper;
import cn.frh.pet.query.SearchMasterMsgQuery;
import cn.frh.pet.service.ISearchMasterMsgService;
import cn.frh.user.domain.Logininfo;
import cn.frh.user.domain.User;
import cn.frh.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private BaiduAiAuditServiceImpl baiduAiAuditService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private RocketMQProducerService rocketMQProducerService;




    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //1.获取发布寻主消息的用户
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //2.添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsg.setState(0);//待审核
        searchMasterMsgMapper.save(searchMasterMsg);
        //3.百度AI智能审核
        Boolean aBoo = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName());
        Boolean bBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        //如果图片和文本信息审核通过 添加日志 并分配最近的店铺
        if (aBoo && bBoo){
            //2.1添加备注及修改状态
            searchMasterMsg.setState(1);//审核通过 待处理
            searchMasterMsg.setNote("审核已通过");
            //2.2根据地图计算最近的店铺并绑定
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point,shops);
            if (nearestShop!=null){
                //给寻主消息绑定店铺
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            searchMasterMsgMapper.update(searchMasterMsg);

            //添加日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setAuditTime(new Date());
            log.setNote("恭喜！审核通过");
            log.setState(1);
            searchMasterMsgAuditLogMapper.save(log);
            if (nearestShop!=null){
                //获取店铺员工手机号
                Employee employee = employeeMapper.loadByShopId(nearestShop.getId());
                //调用工具类发送短信
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请去"+msg.getAddress()+"接回宠物!!!");
                //模拟短信
                System.out.println("有新的寻主订单，请工作人员尽快处理："+searchMasterMsg.getTitle());
            }
            return new AjaxResult();
        }else {
            //添加日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setAuditTime(new Date());
            log.setNote("骚瑞 失败了惹");
            log.setState(0);//失败 未通过 驳回
            searchMasterMsgAuditLogMapper.save(log);
            //SmsUtils.sendSms(user.getPhone(),"你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            System.out.println("你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            return AjaxResult.me().setSuccess(false).setMsg("审核失败，内容非法");
        }
    }

    @Override
    public pageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断当前登录人是平台管理员还是店铺管理员。如果是平台管理员还要设置shopId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.lodaByLogininfoId(logininfo.getId());
        //判断employee中是否有shopid 如果有就是店铺管理员 如果没有 就是平台管理员
        if (employee.getShopId()!=null){
            query.setShopId(employee.getShopId());
        }
        return super.queryPage(query);
    }

    @Override
    public pageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断当前登录人是平台管理员还是店铺管理员。如果是平台管理员还要设置shopId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //设置用户的id
        query.setUserId(user.getId());

        return super.queryPage(query);
    }

    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    @Override
    public void accept(Map<String, String> map) {
        //1.获取参数 效验
        Long msgId = Long.parseLong(map.get("msgId"));
        Long empid = Long.parseLong(map.get("handler"));
        String note = map.get("msgId");
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBymsgId(msgId);
        if (order!=null&&order.getState() == 0){
            throw new BusinessException("订单正在处理 请勿重复操作");
        }
        //2.通过msgId生成宠物 录进系统
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);

        //3.根据参数生成收购订单
        //生成临时对象
        OrderPetAcquisition orderTemp = buildOrderPetAcquisition(msg,pet,empid,note);
        orderPetAcquisitionMapper.save(orderTemp);
        rocketMQProducerService.sendDelayMsg(String.valueOf(order.getId()),4);

        //4.通过处理人上门收宠
//        Employee employee = employeeMapper.loadById(empid);
//        SmsUtils.sendSms(employee.getPhone(),"有新的订单上架了，请尽快完成处理，地址："+msg.getAddress());
        System.out.println("有新的订单上架了，请尽快完成处理，地址："+msg.getAddress());

    }

    private OrderPetAcquisition buildOrderPetAcquisition(SearchMasterMsg msg, Pet pet, Long empid, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);//订单编号
        order.setDigest(note);//摘要
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));//最后确认时间
        order.setState(0);//待处理
        //order.setPaytype(); 现金支付
        order.setPetId(pet.getId());//宠物的id
        order.setUserId(msg.getUserId());//用户的id
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empid);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
